//
//  TTDianpuOrderPageViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/11.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDianpuOrderPageViewController.h"
#import "TTDianpuOrderViewCell.h"
#import "TTOrderModel.h"
#import "TTDianpuCommitOrderViewController.h"
#import "TTCommondDataModel.h"
#import "TTShopCartSubDetailModel.h"
#import "TTOrderDetailModel.h"
#import "TTDianpuOrderDetailViewController.h"

static NSString *cellID = @"dianpi_order_cell_id";

static NSMutableDictionary *needRefreshDic = nil;   // 是否要刷新

@interface TTDianpuOrderPageViewController ()<UITableViewDelegate, UITableViewDataSource, TTDianpuOrderViewCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;
@property (nonatomic, assign) NSInteger status;

@end

@implementation TTDianpuOrderPageViewController

- (instancetype)initWithStatus:(NSInteger)status
{
    self = [super init];
    if (self) {
        
        self.page = 1;
        self.status = status;
        
        // 初始值
        if (needRefreshDic == nil) {
            needRefreshDic = [NSMutableDictionary dictionary];
        }
        [needRefreshDic setObject:@(NO) forKey:[NSString stringWithFormat:@"%ld", (long)status]];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
     @weakify(self)
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            self.page = 1;
            [self getOrderListDatas];
        }];
        
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            self.page++;
            [self getOrderListDatas];
        }];
        
    NSString *statusKey = [NSString stringWithFormat:@"%ld", (long)self.status];
    if (![needRefreshDic[statusKey] boolValue]) {
        [self.tableView.mj_header beginRefreshing];
    }
    
    // 设置页面刷新状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setPageRefreshStatus:) name:@"setDianpuPageRefreshStatusNotify" object:nil];
    
}

// 设置页面刷新状态
- (void)setPageRefreshStatus:(NSNotification *)notify
{
//    NSString *key = [NSString stringWithFormat:@"%ld", (long)self.status];
//    needRefreshDic[key] = @(YES);
    for (NSString *key in needRefreshDic.allKeys) {
        needRefreshDic[key] = @(YES);
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuOrderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = self.dataArray[indexPath.row];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTOrderModel *model = self.dataArray[indexPath.row];
    return model.H;
}



// 获取数据
- (void)getOrderListDatas
{
    @weakify(self)
    [TTCommonNetData getDianpuOrderListWithOrderState:self.status page:self.page success:^(NSURLSessionDataTask * _Nonnull task, NSMutableArray * _Nonnull array) {
        @strongify(self)
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        [self.dataArray addObjectsFromArray:array];
        
        [self.tableView.mj_header endRefreshing];
        if (array.count < 40) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.view];
    
}


- (UIView *)listView
{
    return self.view;
}

- (void)listWillAppear
{
    NSString *statusKey = [NSString stringWithFormat:@"%ld", (long)self.status];
    if ([needRefreshDic[statusKey] boolValue]) {
        // 刷新
        [self.tableView.mj_header beginRefreshing];
        needRefreshDic[statusKey] = @(NO);
    }
    
}

#pragma mark - TTDianpuOrderViewCellDelegate
/// 点击了 取消订单
- (void)cancleButtonClickWithOrderViewCell:(TTDianpuOrderViewCell *_Nullable)cell model:(TTOrderModel *_Nullable)model
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    NSDictionary *dic = @{
        @"param.orderNo" : model.OrderNo,
        @"param.relationName" : [TTLoginSingle sharedSingle].loginModel.RealName
    };
    [[LLNetworkManagerTool sharedManager] postUrlString:plusCancelOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.status == 3) {
            // 全部订单页面，刷新页面
            self.page = 1;
            [self getOrderListDatas];
        } else {
            [self.dataArray removeObject:model];
            if (self.dataArray.count == 0) {
                [self.tableView reloadData];
            } else {
                [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
            }
            
        }
        
        // 设置其他的需要刷新
        for (NSString *key in needRefreshDic.allKeys) {
            if (key.intValue != self.status) {
                needRefreshDic[key] = @(YES);
            }
        }
        // 通知我的页面数字刷新
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPageCountNotify" object:nil];
        // 通知店铺管理页面刷新
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreashDatas" object:nil];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

/// 点击了 删除订单
- (void)deleteButtonClickWithOrderViewCell:(TTDianpuOrderViewCell *_Nullable)cell model:(TTOrderModel *_Nullable)model
{
    
}

/// 查看详情
- (void)lookDetailButtonClickWithOrderViewCell:(TTDianpuOrderViewCell *)cell model:(TTOrderModel *)model
{
    TTDianpuOrderDetailViewController *detailVC = [[TTDianpuOrderDetailViewController alloc] initWithOrderNo:model.OrderNo];
    [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
}

/// 点击了 下单，(改成了查看详情)
- (void)placeOrderuleButtonClickWithOrderViewCell:(TTDianpuOrderViewCell *_Nullable)cell model:(TTOrderModel *_Nullable)model
{
    
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:plusOrderDetail_api parameters:@{@"param.orderNo" : model.OrderNo} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        TTOrderDetailModel *detailModel = [TTOrderDetailModel modelWithJSON:responseObject];
        NSMutableArray *array = [NSMutableArray array];
        for (TTOrderShopModel *shopModel in detailModel.Detail) {
            [self calculateCellHeightWithShopModel:shopModel];
            // 转化model
            TTShopCartSubDetailModel *dm = [TTCommondDataModel orderShopModelToShopCartSubDetailModel:shopModel];
            if (shopModel.SysStatus.intValue == 1) {
                [array addObject:dm];
            }
        }
        for (TTOrderShopModel *shopModel in detailModel.InlayRelateGoodsList) {
            [self calculateCellHeightWithShopModel:shopModel];
            // 转化model
            TTShopCartSubDetailModel *dm = [TTCommondDataModel orderShopModelToShopCartSubDetailModel:shopModel];
            if (shopModel.SysStatus.intValue == 1) {
                [array addObject:dm];
            }
        }
        
        TTDianpuCommitOrderViewController *commitVC = [[TTDianpuCommitOrderViewController alloc] initWithShopArray:array plusShopCustomerName:detailModel.ReceiverName plusShopOrderNo:detailModel.OrderNo sumGoodsPrice:detailModel.SumGoodsPrice];
        [[LLRouteTool getCurrentNavigationController] pushViewController:commitVC animated:YES];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
    
}

// 计算cell高度
- (void)calculateCellHeightWithShopModel:(TTOrderShopModel *)shopModel
{
    CGFloat cellImageH = 65 * kScale + 40;
    
    if (shopModel.GoodsType == 1) {
        shopModel.h = cellImageH;
    } else {
        NSData *data = [shopModel.GoodsDescribe dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *describe = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *content = [describe componentsJoinedByString:@"\n"];
        CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 95 * kScale - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 68;
        
        contentH = contentH < cellImageH ? cellImageH : contentH;
        
        shopModel.h = contentH;
        //定制的
        if (shopModel.GoodsType == 2) {
            shopModel.h = contentH + 30;
        }
    }
    
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTDianpuOrderViewCell class] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    [needRefreshDic removeAllObjects];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




@end
